package com.coocaa.ops.admin.base.schedule;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Date;

/**
 * @author bjh
 * @description
 * @date 2021/6/2 14:20
 */
public abstract class BaseCronScheduleTask implements SchedulingConfigurer {
    /**
     * 处理任务-任务逻辑代码部分
     */
    abstract protected void doRun();

    abstract protected boolean isCanDoRun();

    /**
     * 获取每一次任务触发cron
     *
     * @return
     */
    abstract protected String getCron();

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                //任务逻辑代码部分.
                if (isCanDoRun()) {
                    doRun();
                }
            }
        };
        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任务触发，可修改任务的执行周期.
                //每一次任务触发，都会执行这里的方法一次，重新获取下一次的执行时间
                String cron = getCron();
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };
        scheduledTaskRegistrar.addTriggerTask(task, trigger);
    }
}
